package cn.didi.feidi.androidorder.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.FeidiActionBar;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.core.FeidiMessageHandler;
import cn.didi.feidi.androidorder.io.ReceiverProtocol;
import cn.didi.feidi.androidorder.listener.OnFeidiFragmentNotifySessionListener;
import cn.didi.feidi.androidorder.listener.OnFeidiHandlerSessionListener;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.util.AppUtil;

/**
 * 每个activity最好继承该基类
 * Created by king on 2017/7/15.
 */

public abstract class FeidiBaseActivity extends AppCompatActivity implements OnFeidiHandlerSessionListener {

    private final String TAG = "FeidiBaseActivity.TAG";
    // 上下文实例
    public Context context;
    // 应用全局的实例
    public OrderApplication application;
    private long curClickTimeMillis = 0;
    // actionBar
    private FeidiActionBar feidiActionBar;

    private FeidiMessageHandler mHandler;

    private ArrayList<OnFeidiFragmentNotifySessionListener> mNotifySessionListeners;


    public void addOnFragmentNotifySessionListener(OnFeidiFragmentNotifySessionListener listener) {
        if (mNotifySessionListeners == null)
            mNotifySessionListeners = new ArrayList<OnFeidiFragmentNotifySessionListener>();
        mNotifySessionListeners.add(listener);
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        context = getApplicationContext();
        application = (OrderApplication) this.getApplication();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);

        initHandler();
        initChaoActionBar();
        initViews();
        initData();
        addListener();
    }

    private void initChaoActionBar() {
        feidiActionBar = (FeidiActionBar) findViewById(setFeidiActionBarId());
        if (feidiActionBar != null)
            feidiActionBar.addChaoActionBarCallBack(addChaoActionBarCallBack());
    }

    /**
     * 设置网络提示
     */
    public void setNetworkTip() {
        setNetworkInfo(AppUtil.isNetworkAvailable(context));
    }

    private void setNetworkInfo(boolean isConnect) {
        if (isConnect) {
            OrderApplication.networkTip.setShow(false);
        } else {
            OrderApplication.networkTip.setShow(true);
            OrderApplication.networkTip.setTip("网络请求失败，请检查您的网络设置");
            OrderApplication.networkTip
                    .setClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Intent wifiSettingsIntent = new Intent(
                                    "android.settings.WIFI_SETTINGS");
                            startActivity(wifiSettingsIntent);
                        }
                    });
        }
    }

    /**
     * 增加导航栏回调点击事件
     *
     * @return
     */
    protected FeidiActionBar.FeidiActionBarCallBack addChaoActionBarCallBack() {
        return null;
    }

    abstract protected int setFeidiActionBarId();

    public FeidiActionBar getFeidiActionBar() {
        return feidiActionBar;
    }

    public FeidiMessageHandler getFeidiMessageHandler() {
        return mHandler;
    }

    /**
     * 初始化消息处理器
     */
    private void initHandler() {
        mHandler = OrderApplication.getFeidiMessageHandler();
        mHandler.addOnFeidiHandlerSessionListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        OrderApplication.setCurActivity(this);
        setNetworkTip();
    }

    @Override
    protected void onDestroy() {
        if (mNotifySessionListeners != null)
            mNotifySessionListeners.clear();
        mHandler.removeFeidiHandlerSessionListener(this);
        super.onDestroy();
    }


    /**
     * 发送请求服务器
     */
    synchronized public void executeRequest(AppActionRequest request) {
        //当前界面点击频率不能太高
        if (isMultiplicationClick() && !request.isEmergency()) {
            Log.d(TAG, "发送服务器请求太频繁了 请求连接：" + request.getApiRequest().getRequestURL());
//            makeToast("慢点，本机受不了");
            request.getListener().onFailure(ErrorEvent.PARAM_ACCESS_QUICK, "访问太频繁了");
        } else {
            if (AppUtil.isNetworkAvailable(context)) {
                if (mHandler != null)
                    mHandler.send(request);
                setNetworkInfo(true);
            } else {
                setNetworkInfo(false);
                request.getListener().onFailure(ErrorEvent.PARAM_ACCESS_ERROR_NET, "网络出现了问题");
                makeToast("网络出现了问题");
            }
        }
    }

    /**
     * 发送请求长连接服务器
     */
    synchronized public void executeRequest(int msgId, String obj) {
        if (AppUtil.isNetworkAvailable(context)) {
            if (mHandler != null)
                mHandler.send(msgId, obj);
            setNetworkInfo(true);
        } else {
            setNetworkInfo(false);
            makeToast("网络出现了问题");
        }
    }

    /**
     * 进行长连接的用户登陆
     */
    public void userLogin() {
        mHandler.userLogin();
    }


    @Override
    public void onSessionMessage(int msgId, Object object) {

        switch (msgId) {
            case ReceiverProtocol.DUPLICATE_LOGIN:
//                loginConflict();
                break;
            case ReceiverProtocol.ORDER_RECEIVE_NOTIFICATION:
                Log.d(TAG, "订单" + object + "已被接收");
                break;
            case ReceiverProtocol.ORDER_CANCEL_NOTIFICATION:
                Log.d(TAG, "订单" + object + "被取消");
                break;

            default:
                break;
        }

        // 分发Freagment会话消息
        if (mNotifySessionListeners != null) {
            for (OnFeidiFragmentNotifySessionListener listener : mNotifySessionListeners) {
                listener.onSessionMessage(msgId, object);
            }
        }
    }

    @Override
    public void onSessionMessageException(int msgId, Exception exception) {
        Log.d(TAG, exception == null ? "exception is null !" : "" + exception.getMessage());
        // 分发Freagment会话消息
        if (mNotifySessionListeners != null) {
            for (OnFeidiFragmentNotifySessionListener listener : mNotifySessionListeners) {
                listener.onSessionMessageException(msgId, exception);
            }
        }
    }

    @Override
    public void onSessionClosed() {

    }

    @Override
    public void onSessionConnect() {

    }

    @Override
    public void onSessionTimeout() {

    }

    /**
     * 初始化组件
     */
    protected abstract void initViews();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 添加监听器
     */
    protected abstract void addListener();

    /**
     * 是否点击了多次 小于1秒当作是一次点击了
     **/
    protected boolean isMultiplicationClick() {
        if (curClickTimeMillis == 0) {
            curClickTimeMillis = System.currentTimeMillis();
            return false;
        }
        boolean rs = System.currentTimeMillis() - curClickTimeMillis < 1000;
        curClickTimeMillis = System.currentTimeMillis();
        return rs;
    }

    /**
     * @param text
     */
    public void makeToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 登录冲突,当A登录后,B同账号登录，那么A将收到 登录冲突消息
     */
    private void loginConflict() {
        mHandler.closeService();

        UserManager.clearBingAccountInfo();
        Log.d(TAG, "已在其他设备登录");
        makeToast("已在其他设备登录");
//        showLoginConflictDialog(this);
        goLogin();
    }

    /**
     * 跳转到登录界面，并重启
     */
    private void goLogin() {
        Intent i = getPackageManager()
                .getLaunchIntentForPackage(getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(i);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}
